package com.wsoft.excel.converter;

import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import com.wsoft.annotation.ExcelFieldConvert;
import kotlin.Triple;

import java.util.Map;

/**
 * 用于 Excel 导入 自定义注解 FieldConvert 类型转换
 * @Author z001
 * @Date 2024/11/5 13:31
 */
public class FieldDictConvert implements Converter<String> {

    private final Map<Triple<String, String, String>, Object> dataMap;

    public FieldDictConvert(Map<Triple<String, String, String>, Object> dataMap) {
        this.dataMap = dataMap;
    }

    @Override
    public Class<String> supportJavaTypeKey() {
        return String.class;
    }


    @Override
    public WriteCellData<String> convertToExcelData(String value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws Exception {
        if (contentProperty != null && null != contentProperty.getField() && contentProperty.getField().isAnnotationPresent(ExcelFieldConvert.class)) {
            ExcelFieldConvert excelFieldConvertAnnotation = contentProperty.getField().getAnnotation(ExcelFieldConvert.class);
            String type = excelFieldConvertAnnotation.type();
            String dictCode = excelFieldConvertAnnotation.dictCode();
            //转换
            return new WriteCellData<>(getResult(type,dictCode,value).toString());
        }
        return new WriteCellData<>(value);
    }

    /**
     * 根据 type, dictCode, value 从 dataMap 获取 result
     * @param type 类型
     * @param dictCode 字典编码
     * @param value 当前转换值
     * @return
     */
    public  Object getResult(String type, String dictCode, String value) {
        return dataMap.get(new Triple<>(type, dictCode, value)) == null ? value : dataMap.get(new Triple<>(type, dictCode, value));
    }
}
